package com.poisonh.unifiedauth.dialog;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.utils.ActivityStack;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;
import com.poisonh.unifiedauth.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import wish30.sm.sm;

/**
 * SDK授权登录Dialog
 * Created by PoisonH on 2016/6/24.
 */
public class SDKAuthDialogFragment extends BaseDialogFragment implements View.OnClickListener
{
    private Button mBtnAgree;
    private Button mBtnRefuse;
    private ImageView mIvHead;
    private TextView mTvTxt;

//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
//    {
//        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//        View view = inflater.inflate(R.layout.layout_dialog_auth, null);
//
//        return view;
//    }

    @Override
    protected View loadView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return inflater.inflate(R.layout.layout_dialog_auth, null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        mBtnAgree = (Button) view.findViewById(R.id.btn_agree);
        mBtnRefuse = (Button) view.findViewById(R.id.btn_refuse);
        mIvHead = (ImageView) view.findViewById(R.id.iv_auth_img);
        mTvTxt = (TextView) view.findViewById(R.id.tv_tips_type);

        mBtnRefuse.setOnClickListener(this);
        mBtnAgree.setOnClickListener(this);
        mTvTxt.setText("\"" + ConstantUitls.SDK_APPNAME + "\"");
        if (!TextUtils.isEmpty(ConstantUitls.SDK_APPIMG))
        {
            Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL + ConstantUitls.SDK_APPIMG).into(mIvHead);
        } else
        {
            mIvHead.setBackgroundResource(R.mipmap.ic_launcher);
        }
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.btn_agree:
                answer();
                break;
            case R.id.btn_refuse:
                ToastUtils.showToast(getActivity(), "授权失败");
                ActivityStack.getAppManager().exit();
                break;
        }
    }

    private void answer()
    {
        HttpParams params = new HttpParams();

      //  String mStrUserId = PreferencesUtils.getString(getActivity(), "ID");
        params.put("user_id", mStrUserId);
        params.put("app_id", ConstantUitls.SDK_APPID);
        params.put("token", mStrUserToken);

        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.SDK_CONFIRM, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                try
                {
                    JSONObject json = new JSONObject(response);
                    JSONObject data = new JSONObject(json.getString("results"));
                    sdkGetUserInfo(data.getString("access_token"));
                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String failReason)
            {
                dismiss();
            }
        });
    }

    /**
     * 获取用户信息，并用广播将用户信息发出
     *
     * @param accessToken
     */
    private void sdkGetUserInfo(String accessToken)
    {
        HttpParams params = new HttpParams();


        params.put("app_id", ConstantUitls.SDK_APPID);
        params.put("state", getkey(ConstantUitls.SDK_APPID, accessToken).trim());
        params.put("access_token", accessToken);

        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.SDK_QUERY_AUTH_TOKEN, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                Intent intent = new Intent("certificationsdk");
                intent.putExtra("response", response);
                getActivity().sendBroadcast(intent);
                ActivityStack.getAppManager().exit();
            }

            @Override
            public void onFailure(String failReason)
            {
                dismiss();
            }
        });
    }

    public static String getkey(String appid, String appkey)
    {
        String key = null;
        try
        {
            StringBuffer bf = new StringBuffer();
            bf.append(appid).append(appkey);
            key = Utils.encryptBASE64(sm.getInstance().sm3(bf.toString().getBytes(), bf.toString().getBytes().length));
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return key;
    }
}
